package com.handong.handserialprogram.module.cofigring;

import android.os.Bundle;
import android.widget.Toast;

import com.handong.handserialprogram.constants.KeyConstant;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.model.status.RingResponse;
import com.handong.handserialprogram.module.base.BasePresenter;
import com.handong.handserialprogram.module.base.BaseView;
import com.handong.handserialprogram.module.cofigring.config.ConfigActivity;
import com.handong.handserialprogram.module.serialport.SerialPortUtil;
import com.handong.handserialprogram.utils.EventBusUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by userKey on 2018/6/21.
 */

public class ConfigRingListPresenter extends BasePresenter<ConfigRingListAcivity> {

    private SerialPortUtil mSerialPortUtil;

    public ConfigRingListPresenter(BaseView view) {
        super(view);
        EventBusUtil.register(this);
        mSerialPortUtil = SerialPortUtil.getInstance(mView);
    }

    /**
     * 扫描脚环
     */
    public void scanFootRings() {
        mSerialPortUtil.openSerialPortToReadData();
    }

    /**
     * 接收脚环数据
     * @param list
     */
    @Subscribe(priority = 98, threadMode = ThreadMode.MAIN)
    public void receiveFootRing(CopyOnWriteArrayList<FootRingNewEntity> list) {
        this.mView.showFootRingList(list);
    }

    private void dealException(String message){
        Toast.makeText(mView,message,Toast.LENGTH_SHORT).show();
        mView.dismissLoadingDialog();
    }

    /**
     * 开启配置模式
     * @param id
     */
    public void startConfig(String id){
        mView.showLoadDialog("正在开启配置模式...");
        SerialPortUtil.getInstance(mView).startConfig(id);
    }

    @Subscribe(priority = 100, threadMode = ThreadMode.MAIN)
    public void receiveRingResponse(RingResponse response) {
        switch (response.getResponseCode()) {
            case RingResponse.PARAMETER_SET://配置模式
                if(response.isSuccess()){
                    Bundle bundle=new Bundle();
                    bundle.putString(KeyConstant.PERSON_RING_ID, response.getRingID());
                    mView.openActivity(ConfigActivity.class,bundle);
                }else dealException("开启配置模式失败");

                break;
        }
    }

    @Override
    protected void exit() {
        EventBusUtil.unRegister(this);
        mSerialPortUtil.closeSerialPort();
        super.exit();
    }
}
